﻿using System;
using System.Text.RegularExpressions;

namespace AMing.Core.Extension
{
    public static class StringExtension
    {
        /// <summary>
        /// 转成指定类型
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="val"></param>
        /// <param name="defaultval">转换失败的设置的值</param>
        /// <returns></returns>
        public static T To<T>(this string val, T defaultval = default(T)) where T : struct
        {
            try
            {
                if (string.IsNullOrEmpty(val))
                {
                    return defaultval;
                }
                return (T)Convert.ChangeType(val, typeof(T), null);
            }
            catch (Exception)
            {
                return defaultval;
            }
        }

        /// <summary>
        /// 将指定字符串中的格式项替换为指定数组中相应对象的字符串表示形式。
        /// </summary>
        /// <param name="val"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static string ToFromat(this string val, params object[] args)
        {
            return string.Format(val, args);
        }
    }
}
